﻿using System.Collections.ObjectModel;
using OpenAiMobile.Models;
using OpenAiMobile.Services;
using OpenAiMobile.Util.Json;
using OpenAiMobile.Util.Security;

namespace OpenAiMobile.ViewModels
{
    internal class SearchPageViewModel : BindableBase
    {
        public event Action<MessageItem> ItemAdded = (item) => { };

        public Command SearchCommand { get; set; }

        public ObservableCollection<MessageItem> MessageList { get; }

        public string ChatString
        {
            get => _chatString;
            set => SetProperty(ref _chatString, value);
        }

        private string _chatString;

        private readonly IConfigService _configService;
        private readonly IHttpService _httpService;

        public SearchPageViewModel(IContainerProvider container)
        {
            _configService = container.Resolve<IConfigService>();
            _httpService = container.Resolve<IHttpService>();

            SearchCommand = new Command(OnSearchAsync);
            MessageList = new ObservableCollection<MessageItem>();
            //{
            //    new MessageItem()
            //    {
            //        Header = ImageSource.FromFile(@"header1.jpg"), Location = LayoutOptions.Start, Message = "你好！",
            //        IsAuthor = true, IsOther = false
            //    },
            //    new MessageItem()
            //    {
            //        Header = ImageSource.FromFile(@"header2.jpg"), Location = LayoutOptions.End, Message = "你好呀",
            //        IsAuthor = false, IsOther = true
            //    },
            //    new MessageItem()
            //    {
            //        Header = ImageSource.FromFile(@"header1.jpg"), Location = LayoutOptions.Start, Message = "吃了吗",
            //        IsAuthor = true, IsOther = false
            //    },
            //    new MessageItem()
            //    {
            //        Header = ImageSource.FromFile(@"header2.jpg"), Location = LayoutOptions.End, Message = "吃了",
            //        IsAuthor = false, IsOther = true
            //    },
            //    new MessageItem()
            //    {
            //        Header = ImageSource.FromFile(@"header1.jpg"), Location = LayoutOptions.Start, Message = "吃的啥",
            //        IsAuthor = true, IsOther = false
            //    },
            //    new MessageItem()
            //    {
            //        Header = ImageSource.FromFile(@"header2.jpg"), Location = LayoutOptions.End, Message = "吃的饭",
            //        IsAuthor = false, IsOther = true
            //    },
            //    new MessageItem()
            //    {
            //        Header = ImageSource.FromFile(@"header1.jpg"), Location = LayoutOptions.Start, Message = "哦",
            //        IsAuthor = true, IsOther = false
            //    }
            //};
        }

        public async void OnSearchAsync()
        {
            if (string.IsNullOrWhiteSpace(ChatString))
            {
                return;
            }

            var chatString = ChatString;
            ChatString = string.Empty;

            AddItem(new MessageItem()
            {
                Header = ImageSource.FromFile(@"header1.jpg"),
                Location = LayoutOptions.Start,
                Message = chatString,
                IsAuthor = true,
                IsOther = false
            });

            var aesKey = _configService.AesKey;
            var question = SafeDataHelper.Encrypt(chatString, aesKey);
            var apiKey = SafeDataHelper.Encrypt(_configService.ApiKey, aesKey);
            //AddRequest();

            var queryParamDictionary = new Dictionary<string, object> { { "Question", question } };
            if (!string.IsNullOrWhiteSpace(apiKey))
            {
                queryParamDictionary.Add("ApiKey", apiKey);
            }

            var tokenSource = new CancellationTokenSource();
            if (_configService.RequestTimeout > 0)
            {
                tokenSource.CancelAfter(_configService.RequestTimeout * 1000);
            }

            try
            {
                var url = $@"{_configService.WebApiUrl}/api/proxy/chat/{_configService.AccountId}";
                var ret = await _httpService.GetAsync(url, queryParamDictionary, tokenSource.Token);
                if (tokenSource.IsCancellationRequested)
                {
                    AddItem(new MessageItem()
                    {
                        Header = ImageSource.FromFile(@"header2.jpg"),
                        Location = LayoutOptions.Start,
                        Message = "Http请求超时",
                        IsAuthor = false,
                        IsOther = true
                    });
                    return;
                }

                string correctRet;
                if (ret.Item1)
                {
                    correctRet = SafeDataHelper.Decrypt(ret.Item2, aesKey);
                }
                else
                {
                    var response = JsonHelper.DeserializeObject<ProblemResponse>(ret.Item2);
                    var detail = response.Detail ?? string.Empty;
                    correctRet = SafeDataHelper.Decrypt(detail, aesKey);
                }

                //添加结果
                var message = ret.Item1
                    ? correctRet.TrimStart('\n').TrimStart('\n')
                    : $"获取结果失败：{correctRet}";
                AddItem(new MessageItem()
                {
                    Header = ImageSource.FromFile(@"header2.jpg"),
                    Location = LayoutOptions.Start,
                    Message = message,
                    IsAuthor = false,
                    IsOther = true
                });

                //添加搜索结果到数据库
                //var answer = ret.Item1
                //    ? correctRet.TrimStart('\n').TrimStart('\n')
                //    : string.Empty;
                //var errorMessage = ret.Item1
                //    ? string.Empty
                //    : correctRet;
                //await AddResult2Db(chatString, answer, errorMessage, ret.Item1);
            }
            catch (Exception e)
            {
                var text = $@"请求服务器异常：{e.Message})";
                //_eventAggregator.GetEvent<ShowGrowlWarningEvent>().Publish(text);
                AddItem(new MessageItem()
                {
                    Header = ImageSource.FromFile(@"header2.jpg"),
                    Location = LayoutOptions.Start,
                    Message = text,
                    IsAuthor = false,
                    IsOther = true
                });
            }
            finally
            {
                tokenSource.Dispose();
                //RemoveRequest();
            }
        }

        private void AddItem(MessageItem item)
        {
            MessageList.Add(item);
            ItemAdded.Invoke(item);
        }
    }
}
